<template>
  <div id="app" class="page-home">
    <div class="layout canary">
      <div class="page-content flex canary">
        <section ref="wrap" id="city-list" class="city-list-container">
          <section>
            <div id="locate" class="city-title">
              定位城市<van-icon @click="cross" name="cross" class="cross" />
            </div>
            <div class="city-list city-list-inline clearfix">
              <div
                class="location-city"
                @click="changecityHandler(nowcityName, cityId)"
              >
                {{ nowcityName || "定位中..." }}
              </div>
            </div>
          </section>
          <section class="history-city-list">
            <div id="history" class="city-title">最近访问城市</div>
            <div class="city-list city-list-inline clearfix">
              <div
                @click="changecityHandler(visited.name, visited.cityId)"
                class="city-item"
                v-for="visited in visitedCity"
                :key="visited.ctime"
                :data-nm="visited.name"
                :data-id="visited.cityId"
              >
                {{ visited.name }}
              </div>
            </div>
          </section>
          <section>
            <div id="hot" class="city-title">热门城市</div>
            <div class="city-list city-list-inline clearfix">
              <div
                class="city-item"
                :data-nm="hotcity.name"
                :data-id="hotcity.cityId"
                v-for="hotcity in hotCity"
                :key="hotcity.cityId"
                @click="changecityHandler(hotcity.name, hotcity.cityId)"
              >
                {{ hotcity.name }}
              </div>
            </div>
          </section>
          <section>
            <div class="list_wrap" ref="list_wrap" v-for="num in newCityLists" :key="num.type">
              <div :id="num.type" class="city-title city-title-letter">
                {{ num.type }}
              </div>
              <div class="city-list city-list-block clearfix">
                <div
                  class="city-item"
                  v-for="citys in num.list"
                  :key="citys.cityId"
                  :data-nm="citys.name"
                  :data-id="citys.cityId"
                  @click="changecityHandler(citys.name, citys.cityId)"
                >
                  {{ citys.name }}
                </div>
              </div>
            </div>
          </section>
          <section class="nav">
            <div class="nav-item" v-for="(fixi,index) in fixItem" :key="fixi.id" :data-id="fixi.id" @click="fixiHandler(index,fixi.text)">{{fixi.text}}</div>
            <div
              class="nav-letter nav-item"
              v-for="(indexList,index) in getIndexLists"
              :key="indexList"
              :data-id="indexList"
              @click="indexListHandler(index,indexList)"
            >
              {{ indexList }}
            </div>
          </section>
        </section>
      </div>
    </div>
  </div>
</template>
<script>
import Vue from "vue";
import { IndexBar, IndexAnchor, Cell, Icon, Toast } from "vant";
import http from "../../utils/htttp";
import { mapState, mapMutations } from "vuex";
Vue.use(IndexBar).use(IndexAnchor).use(Cell).use(Icon).use(Toast);
export default {
  data() {
    return {
      visitedCity: [{cityId:110100,name:'北京',ctime:Date.now()}],
      hotCity: [],
      originCityList: [],
      newCityLists: [],
      nowcityName:'',
      fixItem:[
        {
          id:'locate',
          text:'定位'
        },
        {
          id:'history',
          text:'最近'
        },
        {
          id:'hot',
          text:'热门'
        },
      ]
    };
  },
  async mounted() {
    this.nowcityName = await this.getLocation()
    this.originCityList = await this.getoriginCityList();
    this.hotCity = this.originCityList.filter((city) => city.isHot == 1);
    this.newCityLists = this.getnewCityLists(this.originCityList);
    
  },
  methods: {
    //定位当前城市
     getLocation() {
      return new Promise((res, rej) => {
        new BMap.Geolocation().getCurrentPosition((position) => {
          http("/getlocation", {
            params: {
              x: position.point.lat,
              y: position.point.lng,
            },
          }).then((data) =>
            res(data.data.datas.addressComponent.city.substring(0, 2))
          );
        });
      });
    },
    //获取处理后的城市
    getnewCityLists(city) {
      let newArr = [];
      let codesArr = [];
      for (let code = 65; code < 91; code++) {
        codesArr.push(String.fromCharCode(code));
      }
      codesArr.forEach((codes) => {
        let list = city.filter(
          (item) => item.pinyin.slice(0, 1).toUpperCase() === codes
        );
        if (list.length > 0) {
          newArr.push({
            type: codes,
            list: list,
          });
        }
      });
      return newArr;
    },
    //获取原始城市数据
    getoriginCityList() {
      return new Promise((res, rej) => {
        http("/getcitylists").then((data) => res(data.data.cities));
      });
    },
    ...mapMutations("city", ["setCityName", "setCityId"]),
    fixiHandler(index,item) {
      Toast(item)
      let section  = document.querySelectorAll('#city-list section')
      this.$refs.wrap.scrollTop = section[index].offsetTop
    },
    indexListHandler(index,item){
      Toast(item);
      this.$refs.wrap.scrollTop = this.$refs.list_wrap[index].offsetTop

    },
    cross() {
      this.$router.push('/')
    },
    changecityHandler(name, cityId) {
      console.log(cityId);
      let flag = true;
      this.setCityId(cityId);
      this.setCityName(name);
      this.visitedCity.forEach((item) => {
        if (item.name == name) {
          flag = false;
        }
      });
      if (flag) {
        this.visitedCity.unshift({ cityId, name, ctime: Date.now() });
        if (this.visitedCity.length > 3) {
          this.visitedCity = this.visitedCity.splice(0, 3);
        }
      }
      this.$router.push("/");
    },
  },
  computed: {
    getIndexLists() {
      return this.newCityLists.map((item) => item.type)
    },
    ...mapState("city", ["cityName", "cityId", "citylists", ]),
  },
};
</script>
<style>
.city-title {
  padding-right: 0.3rem;
}
.cross {
  float: right;
  margin-top: 7px;
}
.van-toast--html,
.van-toast--text {
  min-width: 45px;
  min-height: 45px;
}
</style>